const User = require('../model').User
const Hash = require('../common/crypto.api').Hash

exports.createUser = function(arancia, username, phone, password, email, interests, avatar) {
  return User.create({ arancia, username, phone, password, email, interests, avatar })
}

exports.existUserByPhone = function(phone) {
  return User.findOne({ phone })
}

exports.validateUserByPassword = async function(phone, rawPassword) {
  try {
    const user = await this.fetchUserByPhone(phone).select('arancia username password')
    const password = Hash(rawPassword + user.username + user.arancia)
    return password === user.password ? user.id : false
  } catch (err) {
    return false
  }
}

exports.fetchUserByPhone = function(phone) {
  return User.findOne({ phone })
}

exports.fetchUserById = function(userId) {
  return User.findById(userId)
}

exports.updateUser = function(query, update) {
  // will not return the new document
  // details:http://mongoosejs.com/docs/4.x/docs/documents.html
  return User.update(query, update)
}

exports.findOneAndUpdate = function(query, update) {
  return User.findOneAndUpdate(query, update)
}

exports.updateById = function(_id, update) {
  return User.findOneAndUpdate({ _id }, update, { new: true })
}

exports.isLonely = async function(userId) {
  try {
    const user = await User.find({ _id: userId, teams: { $size: 0 }})
    return Boolean(user)
  } catch (e) {
    return false
  }
}

exports.becomeAdmin = function(userId, teamId) {
  const data = {
    team: teamId,
    creator: true
  }
  return User.findByIdAndUpdate(userId, { $push: { teams: data }})
}

exports.addTagToSbInTeam = function(tagId, userId, teamId) {
  return User.findOneAndUpdate({
    _id: userId, 'teams.team': teamId
  }, {
    $addToSet: { 'teams.$.management_tags': tagId }
  }, { new: true })
}

exports.removeTagFromSbInTeam = function(tagId, userId, teamId) {
  return User.findOneAndUpdate({
    _id: userId, 'teams.team': teamId
  }, {
    $pull: { 'teams.$.management_tags': tagId }
  }, { new: true })
}

exports.getAllTagsOfSbInTeam = async function(userId, teamId) {
  const { teams } = await User.findOne({
    _id: userId, 'teams.team': teamId
  }).populate({
    path: 'teams.management_tags'
  }).select('teams.management_tags')
  if (!teams || !teams.length) {
    return []
  } else {
    return teams[0].management_tags
  }
}
